package com.evil.kingdom.service.action.impl;

import com.evil.kingdom.pojo.entity.action.AbstractPosition;
import com.evil.kingdom.pojo.entity.action.ActionPosition;
import com.evil.kingdom.pojo.entity.action.Vector;
import com.evil.kingdom.pojo.entity.world.city.City;
import com.evil.kingdom.repository.action.VectorRepository;
import com.evil.common.mongo.service.impl.SingleServiceImpl;
import com.evil.kingdom.service.action.VectorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

/**
 * 导航本
 *
 * @author liyang
 * @date 2024-05-22 17:46
 */
@Slf4j
@Service
public class VectorServiceImpl extends SingleServiceImpl<VectorRepository, Vector> implements VectorService {

    @Override
    public Optional<Vector> isExistByCity(String departName, String destName) {
        return this.isExistByName(Vector.calVectorName(departName, destName));
    }

    @Override
    public Vector findByCity(String departName, String destName) {
        return this.findByName(Vector.calVectorName(departName, destName));
    }

    @Override
    public List<Vector> list() {
        return this.repository.findAll();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Vector> updateByCity(City city) {
        List<Vector> vectors = this.repository.findAllByDepartNameOrDestName(city.getName(), city.getName());
        vectors.forEach(e -> {
            LinkedList<ActionPosition> positions = e.getPositions();
            // 判断更新出发点还是目的点
            AbstractPosition position = e.getDepartName().equals(city.getName()) ? positions.getFirst().getDepart() : positions.getLast().getDest();
            position.setX(city.getX());
            position.setY(city.getY());
        });
        return this.repository.saveAll(vectors);
    }
}
